define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'upload'], function ($, undefined, Backend, Table, Form, Upload) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'news/news/index',
                    add_url: 'news/news/add',
                    edit_url: 'news/news/edit',
                    del_url: 'news/news/del',
                    multi_url: 'news/news/multi',
                    table: 'news',
                }
            });

            var table = $("#table");
            $(".btn-add").data("area", ["100%", "100%"]);
            $(".btn-edit").data("area", ["100%", "100%"]);

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'image', title: __('Image'), operate: false, formatter: Controller.api.formatter.image, events: Table.api.events.image},
                        {field: 'title', title: __('Title'), formatter: Controller.api.formatter.title},
                        {field: 'lx', title: __('Lx'), searchList: {"湛江房产":__('Lx 湛江房产'),"全国房产":__('Lx 全国房产'),"港城生活":__('Lx 港城生活'),"看房日记":__('Lx 看房日记'),"楼市快讯":__('Lx 楼市快讯'),"销售动态":__('Lx 销售动态'),"房产数据":__('Lx 房产数据'),"城市规划":__('Lx 城市规划'),"购房指南":__('Lx 购房指南'),"法律法规":__('Lx 法律法规'),"精英访谈":__('Lx 精英访谈'),"购房萌萌哒":__('Lx 购房萌萌哒'),"品牌直通车":__('Lx 品牌直通车'),"碧桂园":__('Lx 碧桂园'),"行业招聘":__('Lx 行业招聘')}, formatter: Table.api.formatter.normal},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'hot', title: __('Hot'), searchList: {"0":__('Hot 0'),"1":__('Hot 1')}, formatter: Controller.api.formatter.hot},
                        {field: 'flag', title: __('Flag'), searchList: {"0":__('Flag 0'),"1":__('Flag 1')}, formatter: Controller.api.formatter.flag},
                        {field: 'attribute', title: __('Attribute'), searchList: {"0":__('Attribute 0'),"1":__('Attribute 1'),"2":__('Attribute 2')}, visible: false},
                        {field: 'admin.nickname', title: __('Admin.nickname')},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ],
                showColumns: false,
                showToggle: false,
                showExport: false
            });

            //当内容渲染完成给编辑按钮添加`data-area`属性
            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                $(".btn-editone").data("area", ["100%", "100%"]);
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                //修改绑定tinymce事件
                try {
                    if ($(".tinymce,.editor", $("form[role=form]")).size() > 0) {
                        require(['tinymce'], function () {
                            tinymce.init({
                                selector: ".tinymce,.editor", //容器可以是id也可以是class
                                language: 'zh_CN',//语言
                                theme: 'modern',//主体默认主题
                                mobile: {
                                    theme: 'mobile',
                                    language: 'zh_CN',//语言
                                },
                                height: 250,
                                branding: false,
                                fontsize_formats: "8px 10px 12px 14px 18px 24px 36px",
                                plugins: ['advlist link image lists charmap hr anchor searchreplace wordcount visualblocks visualchars code insertdatetime nonbreaking save table contextmenu directionality autolink autosave preview fullscreen media paste textcolor'],//所含插件
                                toolbar: 'undo redo | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | preview media fullpage | fontsizeselect forecolor backcolor | spellchecker code fullscreen',//工具栏
                                // 图像上传处理
                                convert_urls: false, // 关闭url自动检测
                                images_upload_handler: function (blobInfo, success, failure) {
                                    Upload.api.send(blobInfo.blob(), 'h/newspic', function (data) {
                                        var url = Fast.api.cdnurl(data.url);
                                        success(url);
                                        return;
                                    }, function (data, ret) {
                                        failure(ret.msg);
                                        return;
                                    });
                                }
                            });
                            $(document).on("click", ":button[type=submit],input[type=submit]", function () {
                                tinymce.triggerSave();
                            });
                        });
                    }
                } catch (e) {

                }

                Form.api.bindevent($("form[role=form]"));

                var input_id = $('#plupload-image').data("input-id") ? $('#plupload-image').data("input-id") : "";
                var preview_id = $('#plupload-image').data("preview-id") ? $('#plupload-image').data("preview-id") : "";
                if (preview_id) {
                    $(document.body).off("click", "#" + preview_id + " .btn-trash");
                    // 监听事件
                    $("#plupload-image").data("upload-success", function(data, ret) {
                        //这里进行后续操作
                        $(this).hide();
                    });
                    // 移除按钮事件
                    $(document.body).on("click", "#" + preview_id + " .btn-trash", function () {
                        var that = $(this);
                        var path = $("#" + preview_id + " [data-url]");
                        Layer.confirm('是否删除该图片？（删除后不可恢复）',
                            {icon: 3, title: __('Warning'), offset: 0, shadeClose: true},
                            function (index) {
                                var options = {
                                    url: 'news/news/delCover',
                                    data: {
                                        newsid: $("#plupload-image").data('news-id'),
                                        path: path.data("url")
                                    }
                                }
                                Fast.api.ajax(options, function () {
                                    if (input_id) {
                                        $("#" + input_id).val('');
                                    }
                                    that.closest("li").remove();
                                    $("#plupload-image").show();
                                    Layer.close(index);
                                });
                            }
                        );
                    });
                }
                if (input_id) {
                    if ($("#" + input_id).val() != '') {
                        $("#plupload-image").hide();
                    }
                }
            },
            formatter: {
                image: function (value, row, index) {
                    value = value ? Fast.api.cdnurl(value) : '/assets/img/blank.gif';
                    var classname = typeof this.classname !== 'undefined' ? this.classname : 'img-sm img-center';
                    return '<a href="javascript:void(0);"><img class="' + classname + '" src="' + value + '" /></a>';
                },
                hot: function (value, row, index) {
                    return '<a class="btn-change text-success" data-url="'+$.fn.bootstrapTable.defaults.extend.multi_url+'" data-id="' + row.id + '" data-params="hot=' + (row.hot == '0' ? '1' : '0') + '"><i class="fa ' + (row.hot == '0' ? 'fa-toggle-off' : 'fa-toggle-on') + ' fa-2x"></i></a>';
                },
                flag: function (value, row, index) {
                    return '<a class="btn-change text-success" data-url="'+$.fn.bootstrapTable.defaults.extend.multi_url+'" data-id="' + row.id + '" data-params="flag=' + (row.flag == '0' ? '1' : '0') + '"><i class="fa ' + (row.flag == '0' ? 'fa-toggle-off' : 'fa-toggle-on') + ' fa-2x"></i></a>';
                },
                title: function (value, row, index) {
                    return '<a href="https://www.0759home.com/news/info/id/' + row.id + '.html" target="_blank">' + value + '</a>';
                }
            }
        }
    };
    return Controller;
});
